#include <iostream>
#include "TestArrow.hpp"

void TestArrow::_LoadImage()
{
	_image.reset(al_load_bitmap(_filename.c_str()), [](ALLEGRO_BITMAP* p){al_destroy_bitmap(p);});
	if(!_image)
		std::cerr << "Failed to load the test image.\n";
}

/**
 *	Calculate the angle, in radians, from the x-axis to the cursor. This will
 *	actually work for arbitrary positions - not just the cursor's position - but
 *	we won't use it for anything else in this class.
 */
float TestArrow::_CalcAngleToCursor(const Vector& cursor_pos)
{
	Vector vector_to_cursor(cursor_pos-_position);
	VecNormalize(vector_to_cursor);

	static const Vector x_axis(1.0f, 0.0f);
	float angle_radians = std::acos(VecDotProduct(vector_to_cursor, x_axis));
	if(vector_to_cursor.y < 0)
		angle_radians = -angle_radians;

	return angle_radians;
}

/**
 *	We can't chain constructors yet, so we've factored out common intialization into
 *	this function.
 */
void TestArrow::_Initialize()
{
	_filename = "../images/test.png";
	_LoadImage();
	_image_width = al_get_bitmap_width(_image.get());
	_image_height = al_get_bitmap_height(_image.get());
}

TestArrow::TestArrow(const Vector& position)
	: _position(position)
{
	_Initialize();
}

TestArrow::TestArrow()
	: _position(256.0f, 256.0f)
{
	_Initialize();
}

Vector TestArrow::GetPosition() const
{
	return _position;
}

/**
 *	Draw the test arrow pointing towards the passed cursor position.
 */
void TestArrow::DrawFacing(const Vector& cursor_pos)
{
	al_draw_rotated_bitmap(_image.get(), _image_width/2, _image_height/2, _position.x, _position.y, _CalcAngleToCursor(cursor_pos), 0);
}